<template>
  <el-drawer
    :visible.sync="drawerVisible"
    :wrapper-closable="false"
    :close-on-press-escape="false"
    :with-header="false"
    :append-to-body="true"
    size="780px"
    @close="handleClose"
  >
    <div class="filter-dialog-main">
      <div class="pr24">
        <el-form ref="filterRef" :model="targetData" :rules="rules" class="top-content" label-position="top">
          <el-form-item prop="fieldList" class="top-content-left">
            <div slot="label" class="top-title">满足条件时显示以下组件 <div class="tip">（不满足则隐藏）</div> </div>
            <selectWithoutHttp
              v-model="targetData.fieldList"
              :list-data="allFieldList"
              extend-class="dropdown-no-hover"
              filterable
              class="width100"
              multiple
              label-name="showName"
              key-name="key"
              placeholder="请选择组件"
              @change="handelTargetChange" />
          </el-form-item>
          <!-- <el-form-item class="top-content-rule" prop="role">
            <div slot="label" class="top-title">满足规则</div>
            <selectWithoutHttp v-model="targetData.role" :list-data="ruleOptions" class="width100" />
          </el-form-item> -->
        </el-form>
      </div>
      <div class="filter-scroll pr24">
        <div v-for="(group, groupIndex) in targetData.filterListGroup" :key="groupIndex" class="group-item">
          <div class="group-top">
            <div class="label">规则{{ groupIndex+1 }}</div>
            <selectWithoutHttp v-model="group.role" :list-data="ruleOptions" class="width100" />
            <div class="btn-list">
              <img :src="copyGroupIcon" class="copy-icon" alt="" @click="copyGroup(group)">
              <img :src="deleteGroupIcon" class="delete-icon" alt="" @click="deleteGroup(groupIndex)">
            </div>
          </div>
          <div v-if="group.filterList.length" class="group-main">
            <div v-for="(item, index) in group.filterList" :key="index" :class="{'last': group.filterList.length - 1 === index}" class="filter-item">
              <FilterValue
                :filter-item="item"
                :field-list="fieldList"
                :is-show-status="true"
                has-value-type
                key-name="filterField" />
              <div class="btn-list">
                <img :src="copyGroupIcon" class="copy-icon" alt="" @click="copyItem(item, group)">
                <img :src="deleteGroupIcon" class="delete-icon" alt="" @click="deleteItem(index, group)">
              </div>
            </div>
          </div>
          <div class="footer-bar">
            <div class="add-btn" @click="addFilter(group)">添加条件 <i class="add-icon el-icon-plus" /></div>
            <div class="tip">最多添加20条</div>
          </div>
        </div>
      </div>
      <div class="btn-list">
        <div class="add-btn" @click="addFilterGroup">添加规则 <i class="add-icon el-icon-plus" /></div>
        <div class="tip">最多添加10条，规则的关系为或</div>
      </div>
      <div class="btn">
        <el-button type="primary" size="small" @click="toSubmit()">保存</el-button>
        <el-button type="info" size="small" class="cancel-btn-style" @click="handleClose">取消</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import deleteGroupIcon from '@/assets/legalProcess/deleteIcon.png';
import copyGroupIcon from '@/assets/legalProcess/copyIcon.png';
import FilterValue from '../../../filterValue';
import ElMessage from '@/utils/message';
export default {
  name: 'ElementFilterDialog',
  components: { selectWithoutHttp, FilterValue },
  props: {
    fieldList: {
      type: Array,
      default: () => ([])
    },
    allFieldList: {
      type: Array,
      default: () => ([])
    },
    fieldCondition: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    const validateName = (msg, key) => {
      return (rule, value, callback) => {
        const name = this.targetData[key];
        if ((Array.isArray(name) && name.length > 0) || (!Array.isArray(name) && (name || name === 0))) {
          callback();
        } else {
          callback(new Error(msg));
        }
      };
    };
    return {
      deleteGroupIcon, copyGroupIcon,
      ruleOptions: [{ id: 0, value: '符合以下全部条件' }, { id: 1, value: '符合以下任一条件' }],
      drawerVisible: false,
      editIndex: -1,
      targetData: {
        fieldList: [],
        filterListGroup: []
      },
      rules: {
        fieldList: [{ required: true, trigger: 'change', validator: validateName('请选择组件', 'fieldList') }],
        role: [{ required: true, trigger: 'change', validator: validateName('请选择规则类型', 'role') }]
      }
    };
  },
  methods: {
    addFilterGroup() {
      if (!this.targetData.filterListGroup) this.$set(this.targetData, 'filterListGroup', []);
      if (this.targetData.filterListGroup.length >= 10) {
        ElMessage.warning('最多添加10条规则');
        return;
      }
      this.targetData.filterListGroup.push({
        role: 0,
        filterList: []
      });
    },
    deleteGroup(groupIndex) {
      this.targetData.filterListGroup.splice(groupIndex, 1);
    },
    copyGroup(group) {
      if (this.targetData.filterListGroup.length >= 10) {
        ElMessage.warning('最多添加10条规则');
        return;
      }
      this.targetData.filterListGroup.push(_.cloneDeep(group));
    },
    addFilter(group) {
      if (!group.filterList) this.$set(group, 'filterList', []);
      if (group.filterList.length >= 20) {
        ElMessage.warning('最多添加20条规则');
        return;
      }
      group.filterList.push({
        filterField: '',
        math: '=',
        valueType: 0, //  0:值  1:字段
        value: ''
      });
      this.$forceUpdate();
    },
    copyItem(item, group) {
      if (group.filterList.length >= 20) {
        ElMessage.warning('最多添加20条规则');
        return;
      }
      group.filterList.push(_.cloneDeep(item));
    },
    deleteItem(index, group) {
      group.filterList.splice(index, 1);
    },
    openDialog(editIndex, data) {
      if (data) {
        // 编辑
        this.editIndex = editIndex;
        const cloneData = _.cloneDeep(data);
        if (!cloneData.filterListGroup) cloneData.filterListGroup = [];
        // 兼容旧数据，转换为新的数据结构
        if (cloneData.filterList && cloneData.filterList.length && cloneData.filterListGroup.length === 0) {
          cloneData.filterListGroup = [{
            filterList: cloneData.filterList,
            role: cloneData.role || 0
          }];
          delete cloneData.role;
          delete cloneData.filterList;
        }
        this.targetData = cloneData;
      }
      this.drawerVisible = true;
      this.$nextTick(() => {
        if (this.$refs.filterRef) this.$refs.filterRef.clearValidate();
      });
    },
    handleClose() {
      this.drawerVisible = false;
      this.editIndex = -1;
      this.targetData = {};
    },
    toSubmit() {
      if (this.targetData.filterListGroup) {
        this.targetData.filterListGroup = this.targetData.filterListGroup.filter(group => {
          if (!group.filterList) {
            group.filterList = [];
          } else {
            group.filterList = group.filterList.filter(i => !!i.filterField);
          }
          return group.filterList.length > 0;
        });
      } else {
        this.targetData.filterListGroup = [];
      }
      this.$refs.filterRef.validate(valid => {
        if (valid) {
          this.$emit('submit', this.editIndex, this.targetData);
          this.handleClose();
        } else {
          ElMessage.error('请检查信息是否填写完整');
        }
      });
    },
    handelTargetChange(e) {
      const fieldList = this.targetData.fieldList;
      // if(this.fieldCondition)
      if (fieldList.length && this.fieldCondition.length) {
        let ans = '';
        fieldList.forEach(i => {
          this.fieldCondition.forEach((j, index) => {
            if (j.fieldList.includes(i) && this.editIndex !== index) {
              ans = i;
            }
          });
        });
        if (ans) {
          const item = this.allFieldList.find(i => i.key === ans);
          if (!item) return;
          this.targetData.fieldList.splice(fieldList.indexOf(ans), 1);
          ElMessage.error(`${item.name}已设置过条件，无法再次设置`);
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.filter-dialog-main {
  padding: 24px 0px 12px 24px;
}
.pr24 {
  padding-right: 24px;
}
.top-content {
  display: flex;
  border-bottom: 1px solid #EBEEFD;
  padding-bottom: 20px;
  margin-bottom: 20px;
  &::v-deep {
    .el-form-item__label {
      padding-bottom: 0;
      &::before {
        display: none;
      }
    }
  }
  .top-title {
    font-size: 14px;
    color: #666;
    // margin-bottom: 5px;
    display: flex;
    .tip {
      color: #999;
    }
  }
  .top-content-left {
    margin-right: 10px;
    // flex:1;
    width: 420px;
    margin-bottom: 0;
  }
  .top-content-rule {
    margin-bottom: 0;
    width: 240px;
  }
  .width100 {
    width: 100%;
    &::v-deep {
      .el-select,.el-input,.el-input__inner {
        width: 100%;
      }
    }
  }
}
.group-item {
  margin-bottom: 16px;
  border: 1px solid #ddd;
}
.group-top {
  display: flex;
  align-items: center;
  background-color: #f9f9f9;
  height: 40px;
  padding: 0 9px;
  .label {
    font-weight: 550;
    font-size: 14px;
    flex: 1;
  }
}
.group-main {
  padding: 10px 10px 0 10px;
}
.add-btn {
  font-size: 14px;
  color: #406eff;
  cursor: pointer;
  margin-right: 12px;
  font-weight: bold;
  .add-icon {
    font-size: 12px;
  }
}
.tip {
  font-size: 12px;
  color: #999;
}
.footer-bar {
  display: flex;
  align-items: center;
  margin-top: 16px;
  padding: 0px 10px 16px 10px;
}
.btn {
  display: flex;
  margin-top: 20px;
}
.btn-list {
  display: flex;
  align-items: center;
}
.delete-icon {
  width: 12px;
  cursor: pointer;
  margin-left: 9px;
}
.copy-icon {
  width: 12px;
  cursor: pointer;
  margin-left: 9px;
}
.filter-item {
  display: flex;
  margin-bottom: 25px;
  &.last {
    margin-bottom: 0;
  }
  &::v-deep {
    .select-field {
      width: 160px !important;
      .el-input__inner {
        width: 160px !important;
      }
    }
    .select-math {
      width: 120px !important;
      .el-input__inner {
        width: 120px !important;
      }
    }
  }
}
.filter-scroll {
  max-height: calc(100vh - 48px - 190px);
  @include scrollBar($x: hidden, $y: auto);
}
</style>
<style lang="scss">
.dropdown-no-hover {
  .el-select-dropdown__item {
    background-color: #fff !important;
  }
}
</style>
